module.exports = ['$scope','$http', function ($scope,$http) {
    var _API = require('_API')($http);
    var uid,rankid = [];
    // 获取角色
    function getRoles(uid){
        _API.rbac.roles_for_user(uid).success(function (res) {
            $scope.roles = res;
        });
    }
    //获取用户信息
    (function () {
        _API.user.brief().success(function(res){
            $scope.user_data = res;
        });
    })();

    //获取所有岗位
    _API.rank.all().success(function (res) {
        $scope.all_ranks = res;
    });

    //点击用户
    $scope.user_ranks_show = function (user,data) {
        uid = user.id;
        // console.log(uid);
        //修改颜色
        for(var i in data){
            data[i].isActive = false;
        };
        user.isActive = true;
        $scope.username = user.name;
        $scope.rankid = [];
        _API.rank.ranks_for_user(user.id).success(function (res) {
            for (var i in res){
                // console.log(res);
                $scope.rankid.push(res[i].id);
                // console.log($scope.rankid);
            }
            rankid = $scope.rankid;
        });
        getRoles(user.id);
    };

    //选择部门
    $scope.changeRank = function(){
        // console.log(rankid,$scope.rankid);
        // console.log(uid,'???');
        var rid;
        if(!uid){
            showToast('请选择用户','info');
            return;
        }
        if(rankid.length < $scope.rankid.length){
            // console.log('+++');
            for(var i in $scope.rankid){
                if(rankid.indexOf($scope.rankid[i]) == -1){
                    console.log($scope.rankid[i]);
                    rid = $scope.rankid[i];
                }
            }
            _API.rank.add_rank_to_user(uid,rid).success(function () {
                showToast('分配岗位成功','ok');
                // 刷新角色
                getRoles(uid);
            });

        }else{
            // console.log('---');
            for(var i in rankid){
                if($scope.rankid.indexOf(rankid[i]) == -1){
                    rid = rankid[i];
                }
            }
            _API.rank.remove_rank_from_user(uid,rid).success(function () {
                showToast('取消岗位成功','ok');
                // 刷新角色
                getRoles(uid);
            });
        }
        rankid = $scope.rankid;

    }

}];